package cn.yshujia.handler;

import cn.yshujia.utils.MinioUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author YShuJia
 * @create 2025/3/5
 * @description ImgHandler 替换文章中的文件地址![alt](src)(width) 为 <img alt src width />
 */

public class ImgHandler extends BaseTypeHandler<String> {
	
	// 定义正则表达式模式
	Pattern imgPattern = Pattern.compile("!\\[(.*?)]\\((.*?)\\)\\((.*?)\\)");
	// 定义替换后的 HTML img 标签
	String imgMatch = "<img alt='$1' src='$2' width='$3'/>";
	
	// 匹配 src 属性 添加静态资源域名
	Pattern srcPattern = Pattern.compile("src='(.*?)'");
	
	@Override
	public void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
		if (null != s) {
			s = match(imgPattern, imgMatch, s);
			s = s.replaceAll(MinioUtils.STATIC_DOMAIN, "");
		}
		preparedStatement.setString(i, s);
	}
	
	@Override
	public String getNullableResult(ResultSet resultSet, String s) throws SQLException {
		return match(srcPattern, "src='" + MinioUtils.STATIC_DOMAIN + "$1'", resultSet.getString(s));
	}
	
	@Override
	public String getNullableResult(ResultSet resultSet, int i) throws SQLException {
		return match(srcPattern, "src='" + MinioUtils.STATIC_DOMAIN + "$1'", resultSet.getString(i));
	}
	
	@Override
	public String getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
		return match(srcPattern, "src='" + MinioUtils.STATIC_DOMAIN + "$1'", callableStatement.getString(i));
	}
	
	public String match(Pattern pattern, String replacement, String match) {
		if (null == match) {
			return null;
		}
		Matcher matcher = pattern.matcher(match);
		StringBuilder text = new StringBuilder();
		while (matcher.find()) {
			// 替换匹配
			matcher.appendReplacement(text, replacement);
		}
		// 将剩余部分添加到结果中
		matcher.appendTail(text);
		return text.toString();
	}
}